<?php

/**
 * 优惠券信息表
 */
use Common\Bridge;
use lib\core\AdminAction;
use Center\CouponConfig;
use Center\UserCoupon;

define('SITE_AUTH', 'coupon-info');
require('../../../common.inc.php');

class coupon extends AdminAction
{
    private $pdo_r;

    /*
     *   `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ShopId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '电子券所属商铺',
  `Name` varchar(64) NOT NULL COMMENT '优惠券名称',
  `Desc` varchar(128) DEFAULT '' COMMENT '描述信息',
  `Type` int(10) unsigned DEFAULT '0' COMMENT '优惠券类型',
  `StartTime` datetime NOT NULL COMMENT '有效开始日期',
  `EndTime` datetime NOT NULL COMMENT '有效结束日期',
  `ValidSeconds` int(10) NOT NULL DEFAULT '0' COMMENT '有效时长，单位: s',
  `BgUrl` varchar(128) DEFAULT '' COMMENT '背景图片',
  `Value` varchar(10) NOT NULL COMMENT '对应的值',
  `Stock` int(10) DEFAULT '0' COMMENT '库存',
  `Condition` int(11) NOT NULL COMMENT '满足优惠的调价',
  `CreateTime` datetime NOT NULL COMMENT '创建时间',
  `UpdateTime` datetime NOT NULL COMMENT '更新时间',
     */

    private $field = [
        'Id' => '优惠券id',
        'ShopId' => '商铺id',
        'Name' => '优惠券名称',
        'Desc' => '描述信息',
        'Type' => '优惠券类型',
        'StartTime' => '有效开始日期',
        'EndTime' => '有效结束日期',
        'ValidSeconds' => '有效时长',
        'BgUrl' => '背景图片',
        'Value' => '对应的值',
        'Stock' => '库存',
//        'Status' => [0 => '普通商家', 1 => '付费商家', 2 => '过期商家'],
        'Condition' => '满足优惠的调价',
        'CreateTime' => '创建时间',
        'UpdateTime' => '更新时间'
    ];

    private $primary_key = 'Id';
    private $list_url = '/data/modules/shop/coupon.php';

    public function doDefault()
    {
        $param['Id'] = (int)$_GET['Id'];
        $param['ShopId'] = (int)($_GET['ShopId']);
        $param['Name'] = trim($_GET['Name']);

        $field = $this->field;
        $field_key = array_keys($field);
        $field_key_str = '`' . implode('`,`', $field_key) . '`';

        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "1";
        if ($param['Id'] > 0) {
            $where .= " AND Id = " . $param['Id'];
        }

        if ($param['Name'] != '') {
            $where .= " AND Name LIKE '%" . $param['Name'] . "%'";
        }

        if ($param['ShopId']) {
            $where .= " AND ShopId = '" . $param['ShopId'] . "'";
        }

        $primary_key = $this->primary_key;
        $count_sql = "SELECT COUNT($primary_key) AS `num` FROM `CouponConfig` WHERE $where";

        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $sql = "SELECT $field_key_str FROM `CouponConfig` WHERE $where LIMIT $offset,$limit";
        $data = $this->readDb($sql);

        $smarty = $this->app->page();
        if ($count > 0) {
            if (!empty($data)) {
                $smarty->value('list', $data);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }

        $smarty->value('param', $param);
        $smarty->value('field', $field);
        $smarty->output('shop/couponList.tpl');
    }

    /**
     *
     */
    public function doEdit()
    {
        $id = (int)$_GET['Id'];
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }

        $sql = "SELECT * FROM CouponConfig WHERE Id = $id";
        $list = $this->readDb($sql);

        $smarty = $this->app->page();
        $smarty->value('info', current($list));
        $smarty->output('shop/couponedit.tpl');
    }

    public function doAdd()
    {
        $smarty = $this->app->page();
//        $smarty->value('info', current($list));
        $smarty->output('shop/couponadd.tpl');
    }


    public function doUpdate()
    {
        $id = intval($_POST['Id']);
        if (empty($id) || empty($_POST['Name'])) {
            HDshowMsg('修改失败1！', ['type' => 'error', 'url' => $this->list_url]);
        }

        //上传图片
        $img = $_FILES['BgUrl'];
        if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
            // 复制图片
            $imgUrlAddre = self::saveImageUrl($id, $_FILES['BgUrl']);
        } else {
            $imgUrlAddre = false;
        }

        $data = [
            'ShopId' => intval($_POST['ShopId']),
            'Name' => trim($_POST['Name']),
            'Desc' => trim($_POST['Desc']),
            'Type' => intval($_POST['Type']),
            'StartTime' => trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'ValidSeconds' => intval($_POST['ValidSeconds']),
            'Value' => trim($_POST['Value']),
            'Stock' => intval($_POST['Stock']),
            'Condition' => intval($_POST['Condition']),
//            'Status' => intval($_POST['Status']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        if ($imgUrlAddre !== false) {
            $data['BgUrl'] = $imgUrlAddre;
        }

        $rel = Center\CouponConfig::update($id, $data);
        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doInput()
    {
        if (empty($_POST['Name'])) {
            HDshowMsg('修改失败1！', ['type' => 'error', 'url' => $this->list_url]);
        }

        $data = [
            'ShopId' => intval($_POST['ShopId']),
            'Name' => trim($_POST['Name']),
            'Desc' => trim($_POST['Desc']),
            'Type' => intval($_POST['Type']),
            'StartTime' => trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'ValidSeconds' => intval($_POST['ValidSeconds']),
            'Value' => trim($_POST['Value']),
            'Stock' => intval($_POST['Stock']),
            'Condition' => intval($_POST['Condition']),
//            'Status' => intval($_POST['Status']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        $id = Center\CouponConfig::add($data);
        if ($id !== false && $id > 0) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
        //上传图片
        $img = $_FILES['BgUrl'];
        if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0 && $id) {
            // 复制图片
            $imgUrlAddre = self::saveImageUrl($id, $_FILES['BgUrl']);
            \Center\CouponConfig::update($id, ['BgUrl' => $imgUrlAddre]);
        }

        if ($id) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    /**
     * 利用SQL语句读取数据库并返回相应数据
     *
     * @param $sql
     * @return mixed
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_W);
        }

        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }

    /**
     * @param $filename
     * @return bool|string
     */
    private static function saveImageUrl($id, $filename)
    {
        ///
        $upload_dir = \Common\ResourcePathManager::getCouponBgImgSavePath();

        $hash = \Common\PhotoImage::getImageHash($id);
        //$src_img = $upload_dir . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
        $image_status = \Common\PhotoImage::checkImage($filename);

        if ($image_status['code'] == 4) {
            $image_status = \Common\PhotoImage::checkImageByUrl($filename);

            if ($image_status['code'] == 4) {
                return false;
            }
        }

        //配置图片上传目录
        $cfg = [
            'base' => $upload_dir,
            'thumb' => [
                'source' => [
                    'url' => '{hash1}/{hash2}/{id}.jpg'
                ],
                '300' => [
                    'width' => 300,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_300.jpg'
                ],
                '800' => [
                    'width' => 800,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_800.jpg'
                ]
            ],
            'hash1' => $hash['hash1'],
            'hash2' => $hash['hash2'],
            'id' => $id
        ];

        if ($image_status['status'] == true) {
            $result = \Common\PhotoImage::imageResize($cfg, $image_status);

            if ($result) {
                $res_arr = [
                    "http://img.jinguonet.com/coupon/bg/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg",
                    "http://img.jinguonet.com/coupon/bg/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_300.jpg",
                    "http://img.jinguonet.com/coupon/bg/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_800.jpg"
                ];

                return "http://img.jinguonet.com/coupon/bg/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
            }


        }

        return false;
    }
}

$app->run();